/**
 * Copyright 2011 The Apache Software Foundation
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package enterprise.web_jpa_war.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import enterprise.web_jpa_war.entity.Person;
import enterprise.web_jpa_war.entity.Role;
import enterprise.web_jpa_war.entity.RoleRelationship;

/**
 * The servlet class to list Persons from database
 */
public class ListPersonServlet extends AbstractServlet {
    
    private static final String SQL_QUERY_PERSON_ROLES = "SELECT * FROM PERSON_ROLES " +
		    				"WHERE PERSON_ID = ? ";
	private static final String SQL_QUERY_PERSON = "SELECT * FROM PERSON ORDER BY ID";

	/** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    	
    	Set<Person> persons = new LinkedHashSet<Person>();
    	Person person = null;
    	Connection connection = null;
    	PreparedStatement statement4Person = null;
    	ResultSet personResults = null;
    	
		try {
			connection = this.getConnection();
	    	statement4Person = connection.prepareStatement(
	    			SQL_QUERY_PERSON);
	    	personResults = statement4Person.executeQuery();
	    	
	    	while(personResults.next()){
	    		person = new Person();
	    		person.setId(personResults.getLong("ID"));
	    		person.setLastName(personResults.getString("LAST_NAME"));
	    		person.setFirstName(personResults.getString("FIRST_NAME"));
	    		person.setAccountName(personResults.getString("ACCOUNT_NAME"));
	    		person.setPassword(personResults.getString("PASSWORD"));
	    		
	    		//find corresponding roles
	    		generateCorrespondingRoles(connection, person);
	    		
	    		persons.add(person);
	    	}
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException("get persons failed", e);
		} finally {
			closeStatement(statement4Person);
			closeConnection(connection);
		}
    	
    	request.setAttribute("personList",persons);
        //Forward to the jsp page for rendering
        request.getRequestDispatcher("/person/ListPerson.jsp").forward(request, response);
    }
    
    private void generateCorrespondingRoles(Connection connection, Person person) throws SQLException{
    	Role role = null;
    	RoleRelationship roleRelationship = null;
    	List<RoleRelationship> roleRelationships = null;
    	PreparedStatement statement4Role = null;
    	ResultSet roleResults = null;
    	
    	statement4Role = connection.prepareStatement(SQL_QUERY_PERSON_ROLES);
		statement4Role.setLong(1, person.getId());
		roleResults = statement4Role.executeQuery();
		
		roleRelationships = new ArrayList<RoleRelationship>();
		while(roleResults.next()){
			role = new Role();
			role.setId(roleResults.getLong("PERSON_ROLE_ID"));
			role.setName(roleResults.getString("ROLE_NAME"));
			
			roleRelationship = new RoleRelationship();
			roleRelationship.setRole(role);
			roleRelationships.add(roleRelationship);
		}
		person.setRoleRelationships(roleRelationships);
    }
    
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }
    
    /** Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }
    
    /** Returns a short description of the servlet.
     */
    public String getServletInfo() {
        return "ListPerson servlet";
    }
}
